const fs = require("fs");
const path = require("path");
const util = require("util");
const process = require("process");
const es = require("event-stream");
const Debug = require("debug")("[index.js]");
Debug.enabled = true;
const GoodLineProcess = require("./good-line-process").GoodLineProcess;
const AfterRead = require("./after-read-mysql").AfterRead;

Debug("cwd",process.cwd());

/**
 * 
 * @param {String} full_path_of_mht 
 */
function Parse(full_path_of_mht) {
    return new Promise((resolve) => {
        let count = 0;
        let readMhtStream = fs.createReadStream(
            full_path_of_mht
        );
        let filename = path.basename(full_path_of_mht);
        let line_promise;
        let s = readMhtStream
            .pipe(es.split())
            .pipe(es.mapSync(
                /**
                 * @param {String} line
                 */
                function (line) {
                    s.pause();
                    count++;
                    let l = line;
                    while (l.endsWith("\r")) {
                        l = l.slice(0, l.length - 1);
                    }
                    line_promise = GoodLineProcess(l, count, filename).then(() => {
                        // Debug("resume!", count);
                        s.resume();
                    })
                }));
        s.on("close", () => {
            Debug("stream close");
            line_promise.then(() => {
                Debug("全部读取结束了?");
                Debug("last chunk_count", count);
                AfterRead().then(args => {
                    Debug("全部写完了");
                    resolve("over")
                })
            })
        });
    })

}

// Parse(
//     path.join(__dirname, "./dev-mht/150829-150913.mht")
// )

module.exports = {
    Parse
}